﻿/**************************common方法**************************/

layui.define(["jquery"], function (exports) {
    var $ = layui.jquery;
    var loadingUse_tempIndex;
    var obj = {

        //身份证号验证
        identificationNoVerify: function (value) {
            return /(^\d{15}$)|(^\d{17}(x|X|\d)$)/.test(value);
        },

        //金额验证，两位小数
        amountVerify: function (value) {
            return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value);
        },

        //根据日期获取星期
        getWeek: function (date) {
            var day = new Date(Date.parse(date));
            var today = ['日', '一', '二', '三', '四', '五', '六'];
            return today[day.getDay()];
        },

        compare: function (prop, type) {
            return function (obj1, obj2) {
                var val1 = obj1[prop];
                var val2 = obj2[prop];
                if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
                    val1 = Number(val1);
                    val2 = Number(val2);
                }
                if ("desc" == type) {
                    if (val1 > val2) {
                        return -1;
                    } else if (val1 < val2) {
                        return 1;
                    } else {
                        return 0;
                    }
                } else {
                    if (val1 < val2) {
                        return -1;
                    } else if (val1 > val2) {
                        return 1;
                    } else {
                        return 0;
                    }
                }

            }
        },
        /**
         * 格式化日期
         * @param fmt
         * @returns {string | void}
         * @constructor
         */
        formatDate: function (d, fmt) {
            var o = {
                "M+": d.getMonth() + 1, //月份
                "d+": d.getDate(), //日
                "h+": d.getHours(), //小时
                "m+": d.getMinutes(), //分
                "s+": d.getSeconds(), //秒
                "q+": Math.floor((d.getMonth() + 3) / 3), //季度
                "S": d.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        },

        /**
         * 获取当前时间 yyyy-MM-dd字符串
         * @param d 时间
         * @returns {string | void}
         * @constructor
         */
        getCurrentDateStr: function (d) {
            var year = d.getFullYear();
            var month = (d.getMonth() + 1).toString().padStart(2, '0');
            var day = d.getDate().toString().padStart(2, '0');
            // console.log('日期'+JSON.stringify(year+'-'+month+'-'+day))
            return year + '-' + month + '-' + day;
        },

        /**
         * 获取过去时间 yyyy-MM-dd字符串
         * @param d 时间
         * @param pastDays 时间间隔
         * @returns {string | void}
         * @constructor
         */
        getPastDateStr: function (d, pastDays) {
            var times = d.getTime();
            var pastDate = new Date();
            pastDate.setTime(times - (pastDays * 86400000));
            var year = pastDate.getFullYear();
            var month = (pastDate.getMonth() + 1).toString().padStart(2, '0');
            var day = pastDate.getDate().toString().padStart(2, '0');
            // console.log('日期2'+JSON.stringify(year+'-'+month+'-'+day))
            return year + '-' + month + '-' + day;
        },

        /**
         * 获取过去时间 yyyy-MM-dd字符串
         * @param d 时间
         * @param pastDays 时间间隔
         * @returns {string | void}
         * @constructor
         */
        getNextDateStr: function (d, pastDays) {
            var times = d.getTime();
            var pastDate = new Date();
            pastDate.setTime(times + (pastDays * 86400000));
            var year = pastDate.getFullYear();
            var month = pastDate.getMonth() + 1;
            var day = pastDate.getDate();
            return year + '-' + month + '-' + day;
        },

        /**
         * 生成UUID
         * @param len 长度
         * @param radix 基数 2进制 8进制 10进制 16进制
         * @returns uuid
         * 调用：var uuidstr = uuid(32,16);//生成32位长度的基数为16进制的uuid
         *  7FEA14A4722E273EE28C3F72E9E9141F
         */

        UUID: function (len, radix) {
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            var uuid = [], i;
            radix = radix || chars.length;

            if (len) {
                // Compact form
                for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
            } else {
                // rfc4122, version 4 form
                var r;

                // rfc4122 requires these characters
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';

                // Fill in random data.  At i==19 set the high bits of clock sequence as
                // per rfc4122, sec. 4.1.5
                for (i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random() * 16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }

            return uuid.join('');
        },

        cutZero: function (arg) {
            var arr = arg.split(".")
            //去除后缀的0
            while (arr[1].endsWith("0")) {
                arr[1] = arr[1].substr(0, arr[1].length - 1)
            }
            //判断小数点后还有没有0
            if (arr[1].length == 0) {
                return arr[0]
            }
            return arr.join(".")
        },

        downloadFile: function (url, name) {
            if (!name) name = new Date().getTime();

            if (isIE()) {
                window.open(url, "_blank");
            } else {

                var temp = document.createElement("a");
                if ($("#downPdf").length == 0) {
                    $("body").append('<a download="" href="" target="blank" id="downPdf" style="display:none"></a> ');
                }

                var a = document.getElementById("downPdf");
                a.href = url;
                a.download = name;
                a.click();

            }
        },
        similar: function (s, t, f) {
            if (!s || !t) {
                return 0
            }
            //排除PS
            s = s.replace(/P\/S/gi, '');
            t = t.replace(/P\/S/gi, '');
            var l = s.length > t.length ? s.length : t.length
            var n = s.length
            var m = t.length
            var d = []
            f = f || 3
            var min = function (a, b, c) {
                return a < b ? (a < c ? a : c) : (b < c ? b : c)
            }
            var i, j, si, tj, cost
            if (n === 0) return m
            if (m === 0) return n
            for (i = 0; i <= n; i++) {
                d[i] = []
                d[i][0] = i
            }
            for (j = 0; j <= m; j++) {
                d[0][j] = j
            }
            for (i = 1; i <= n; i++) {
                si = s.charAt(i - 1)
                for (j = 1; j <= m; j++) {
                    tj = t.charAt(j - 1)
                    if (si === tj) {
                        cost = 0
                    } else {
                        cost = 1
                    }
                    d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
                }
            }
            var res = (1 - d[n][m] / l);
            return res.toFixed(f)
        },

        //判断是否有兄弟元素与自己产生堆叠，如果有返回此兄弟元素，如果没有返回false;
        getMostTouchDom: function (zj) {
            var choseList = [];
            zj.parent().find('.mov').each(function () {
                if (zj[0] != this) {
                    var result = situation(zj, $(this));
                    if (result[0] < 4 && result[0] >= 0) {
                        choseList.push({
                            touchAbs: Math.abs(result[1]),　　//与重叠元素中心点的距离的绝对值
                            dom: this,　　　　　　　　　　　　　　//此重叠元素对象
                            touchRange: result[1]　　　　　　　 //与重叠元素中心点距离
                        });
                    }
                }
            });
            if (choseList.length == 0) {
                return false;
            }
            //数组以绝对值大小降序排列
            choseList.sort(function (a, b) {
                return a.touchAbs - b.touchAbs;
            });
            //返回与zj中心点距离最近的元素
            return choseList[0];
            //遍历检查：除了自身身和接触对象外，是否有其他元素会在吸附后产生重叠。
        },
        //通过周取日期范围   year 年   weeks 周
        weekGetDate: function (year, weeks) {
            var date = new Date(year, "0", "1");
            // 获取当前星期几,0:星期一
            var time = date.getTime();
            //当这一年的1月1日为周日时则本年有54周,否则没有54周,没有则去除第54周的提示
            var _week = date.getDay();

            if (_week != 0) {//一年53周情况
                if (weeks == 54) {
                    return '今年没有54周';
                }
                var cnt = 0;// 获取距离周末的天数
                if (_week == 0) {
                    cnt = 7;
                } else if (_week == 1) {
                    cnt = 6;
                } else if (_week == 2) {
                    cnt = 5;
                } else if (_week == 3) {
                    cnt = 4;
                } else if (_week == 4) {
                    cnt = 3;
                } else if (_week == 5) {
                    cnt = 2;
                } else if (_week == 6) {
                    cnt = 1;
                }
                cnt += 1;//加1表示以星期一为一周的第一天    // 将这个长整形时间加上第N周的时间偏移
                time += cnt * 24 * 3600000; //第2周开始时间
                var nextYear = new Date(parseInt(year, 10) + 1, "0", "1");
                var nextWeek = nextYear.getDay();
                var lastcnt = 0;//获取最后一周开始时间到周末的天数
                if (nextWeek == 0) {
                    lastcnt = 6;
                } else if (nextWeek == 1) {
                    lastcnt = 0;
                } else if (nextWeek == 2) {
                    lastcnt = 1;
                } else if (nextWeek == 3) {
                    lastcnt = 2;
                } else if (nextWeek == 4) {
                    lastcnt = 3;
                } else if (nextWeek == 5) {
                    lastcnt = 4;
                } else if (nextWeek == 6) {
                    lastcnt = 5;
                }
                if (weeks == 1) {//第1周特殊处理    // 为日期对象 date 重新设置成时间 time
                    var start = date.Format("yyyy-MM-dd");
                    date.setTime(time - 24 * 3600000);

                    return start + "—" + date;
                } else if (weeks == 53) {//第53周特殊处理
                    //第53周开始时间
                    var start = time + (weeks - 2) * 7 * 24 * 3600000;
                    //第53周结束时间
                    var end = time + (weeks - 2) * 7 * 24 * 3600000 + lastcnt * 24 * 3600000 - 24 * 3600000;
                    date.setTime(start);
                    var _start = date.Format("yyyy-MM-dd");
                    date.setTime(end);
                    var _end = date.Format("yyyy-MM-dd");
                    return _start + "—" + _end;
                } else {
                    var start = time + (weeks - 2) * 7 * 24 * 3600000; //第n周开始时间
                    var end = time + (weeks - 1) * 7 * 24 * 3600000 - 24 * 3600000; //第n周结束时间
                    date.setTime(start);
                    var _start = date.Format("yyyy-MM-dd");
                    date.setTime(end);
                    var _end = date.Format("yyyy-MM-dd");
                    return _start + "—" + _end;
                }
            } else {//一年54周情况
                var cnt = 0;// 获取距离周末的天数
                if (_week == 0 && weeks == 1) {//第一周
                    cnt = 0;
                } else if (_week == 0) {
                    cnt = 7;
                } else if (_week == 1) {
                    cnt = 6;
                } else if (_week == 2) {
                    cnt = 5;
                } else if (_week == 3) {
                    cnt = 4;
                } else if (_week == 4) {
                    cnt = 3;
                } else if (_week == 5) {
                    cnt = 2;
                } else if (_week == 6) {
                    cnt = 1;
                }
                cnt += 1;//加1表示以星期一为一周的第一天
                // 将这个长整形时间加上第N周的时间偏移
                time += 24 * 3600000; //第2周开始时间
                var nextYear = new Date(parseInt(year, 10) + 1, "0", "1");
                var nextWeek = nextYear.getDay();
                var lastcnt = 0;//获取最后一周开始时间到周末的天数
                if (nextWeek == 0) {
                    lastcnt = 6;
                } else if (nextWeek == 1) {
                    lastcnt = 0;
                } else if (nextWeek == 2) {
                    lastcnt = 1;
                } else if (nextWeek == 3) {
                    lastcnt = 2;
                } else if (nextWeek == 4) {
                    lastcnt = 3;
                } else if (nextWeek == 5) {
                    lastcnt = 4;
                } else if (nextWeek == 6) {
                    lastcnt = 5;
                }
                if (weeks == 1) {//第1周特殊处理
                    var start = date.Format("yyyy-MM-dd");
                    date.setTime(time - 24 * 3600000);
                    return _start + "—" + date;
                } else if (weeks == 54) {//第54周特殊处理
                    //第54周开始时间
                    var start = time + (weeks - 2) * 7 * 24 * 3600000;
                    //第53周结束时间
                    var end = time + (weeks - 2) * 7 * 24 * 3600000 + lastcnt * 24 * 3600000 - 24 * 3600000;
                    date.setTime(start);
                    var _start = date.Format("yyyy-MM-dd");
                    date.setTime(end);
                    var _end = date.Format("yyyy-MM-dd");
                    return _start + "—" + _end;
                } else {
                    var start = time + (weeks - 2) * 7 * 24 * 3600000; //第n周开始时间
                    var end = time + (weeks - 1) * 7 * 24 * 3600000 - 24 * 3600000; //第n周结束时间
                    date.setTime(start);
                    var _start = date.Format("yyyy-MM-dd");
                    date.setTime(end);
                    var _end = date.Format("yyyy-MM-dd");
                    return _start + "—" + _end;
                }
            }
        },
        getWeekOfYear: function () {
            //获取当前时间是今年第几周
            var today = new Date();
            var firstDay = new Date(today.getFullYear(), 0, 1);
            var dayOfWeek = firstDay.getDay();
            var spendDay = 1;
            if (dayOfWeek != 0) {
                spendDay = 7 - dayOfWeek + 1;
            }
            firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
            var d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
            var result = Math.ceil(d / 7);
            return result + 1;
        },
        loading_open: function (tip) {
            loadingUse_tempIndex = layer.msg(tip || "系统正在处理中，请稍后...", {
                icon: 4,
                shade: [0.3, '#000'],
                time: 0,
                isOutAnim: false
            });
        },
        loading_close: function () {
            layer.close(loadingUse_tempIndex);
        },
        log: function (str) {
            console.log(str);
        },
        isEmpty: function (value) {
            if (typeof (value) === "undefined" || value == null || value == "") {
                return true;
            }
            return false;
        },
        /**
         * 缩略图方法展示
         * @param a
         * @param b
         * @param c
         * @param d
         * @returns {boolean}
         */
        showImgBig: function ($view, bigDiv, imgWidth, imgHeight) {
            var windowW = $(window).width();//获取当前窗口宽度
            var windowH = $(window).height();//获取当前窗口高度
            var realWidth = imgWidth;//获取图片真实宽度
            var realHeight = imgHeight;//获取图片真实高度
            var imgWidth, imgHeight;
            var scale = 0.8;//缩放尺寸，当图片真实宽度和高度大于窗口宽度和高度时进行缩放
            var maxW = windowW * scale;
            var maxH = windowH * scale;
            var percentW = maxW / realWidth;
            var percentH = maxH / realHeight;
            //console.log(windowW, windowH, realWidth, realHeight, percentW, percentH);
            var percent = Math.max(percentW, percentH);
            imgWidth = realWidth * percent;
            imgHeight = realHeight * percent;
            if (imgWidth > maxW) {
                imgHeight = maxW / imgWidth * imgHeight;
                imgWidth = maxW;
            }
            if (imgHeight > maxH) {
                imgWidth = maxH / imgHeight * imgWidth;
                imgHeight = maxH;
            }
            //以最终的宽度对图片缩放
            $(bigDiv).css("width", imgWidth).css("height", imgHeight);
            var w = (windowW - imgWidth) / 2;//计算图片与窗口左边距
            var h = (windowH - imgHeight) / 2;//计算图片与窗口上边距
            $(bigDiv).parent().css({"top": h, "left": w});//设置#innerdiv的top和left属性
            $view.find(".big-img-div").fadeIn("fast");//淡入显示#outerdiv及.pimg
        },
        // 计算表格高度
        calcTableHeight: function (diff) {
            //选项卡tab高度
            let tabHeight = $(".febs-tabs-wrap").height() == null ? "0" : $(".febs-tabs-wrap").height();
            //标题头的高度
            let appHeight = $("#app-header").height() == null ? "0" : $("#app-header").height();
            // 搜索框高度(带padding)
            let searchHeight = $(".febs-body-search").outerHeight(true) == null ? "0" : $(".febs-body-search").outerHeight(true);
            //  20为距上下的margin
            let tempheight = parseFloat(searchHeight) + parseFloat(tabHeight) + parseFloat(appHeight) + 40;
            if (!!diff) {
                tempheight += diff;
            }
            // 返回table实际格式 例：full-170
            let heightStr = "full-" + tempheight;
            return heightStr;
        },
        // 计算div高度
        calcDivHeight: function (diff) {
            var appSidebarHeight = $("#app-sidebar").height() == null ? "0" : $("#app-sidebar").height();
            //选项卡tab高度
            var tabHeight = $(".febs-tabs-wrap").height() == null ? "0" : $(".febs-tabs-wrap").height();
            //标题头的高度
            var appHeight = $("#app-header").height() == null ? "0" : $("#app-header").height();
            // 搜索框高度(带padding)
            var searchHeight = $(".febs-body-search").outerHeight(true) == null ? "0" : $(".febs-body-search").outerHeight(true);
            //  20为距上下的margin
            var tempheight = parseFloat(searchHeight) + parseFloat(tabHeight) + parseFloat(appHeight) - 23 + (diff == null ? 0 : diff);
            // 返回table实际格式 例：full-170
            var height = appSidebarHeight - tempheight;
            return height;
        },
        /**
         * 自动计算设置弹出窗口内容高度
         * @param $view
         */
        autoOpenPageHeight: function ($view) {
            let newLayerContentHeight = $view.parent().parent().height() - 100;
            $view.parent().parent().find(".layui-layer-content").css("height", newLayerContentHeight);
        },
        isImg: function (fileName) {
            var img1 = new RegExp(".jpg")
            var img2 = new RegExp(".png")
            var img3 = new RegExp(".JPG")
            var img4 = new RegExp(".PNG")
            if (img1.test(fileName) || img2.test(fileName) || img3.test(fileName) || img4.test(fileName)) {
                return true
            }
            return false
        },
        isPdf: function (fileName) {
            var img1 = new RegExp(".pdf")
            var img2 = new RegExp(".PDF")
            if (img1.test(fileName) || img2.test(fileName)) {
                return true
            }
            return false
        },
        previewImgOrPdf: function (filePath, fileName, $view) {
            if (obj.isPdf(fileName)) {
                top.layer.open({
                    type: 2,
                    title: fileName + "预览",
                    area: ['80%', '90%'],
                    fixed: false, //不固定
                    maxmin: true,
                    content: filePath
                });
            } else if (obj.isImg(fileName)) {
                // $view.find(".imgView").remove()
                // var img = "<body><img  class='imgView' src='" + ctx + filePath + "'/></body>"
                // $view.append(img)
                // $view.find(".imgView").hide();
                // $view.find(".imgView").viewer();
                // $view.find(".imgView").trigger("click");
                $view.find(".big-img-div img").attr("src", ctx + filePath);

            } else {
                var a = document.createElement("a")
                a.href = ctx + filePath
                a.download = fileName
                a.click()
            }
        },

        previewImgOrPdf2: function (filePath, fileName) {
            if (obj.isPdf(fileName) || obj.isImg(fileName)) {
                top.layer.open({
                    type: 2,
                    title: fileName + "预览",
                    area: ['80%', '90%'],
                    fixed: false, //不固定
                    maxmin: true,
                    content: filePath
                });
            } else {
                var a = document.createElement("a")
                a.href = ctx + filePath
                a.download = fileName
                a.click()
            }
        },
    }


    exports('commonJS', obj);
});
